package br.com.poolme.connection;

import java.io.IOException;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DataElement;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.ServiceRecord;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnectionNotifier;

public class BluetoothConnectionServidor extends BluetoothConnection {

    private StreamConnectionNotifier notifier;

    public BluetoothConnectionServidor() {
    }

    public void stop() {
        try {
            LocalDevice.getLocalDevice().setDiscoverable(
                    DiscoveryAgent.NOT_DISCOVERABLE);
        } catch (BluetoothStateException ignored) {
        }
        try {
            notifier.close();
        } catch (IOException ignored) {
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (IOException ignored) {
            }
        }

    }

    public void run() {
        try {
            localDevice = LocalDevice.getLocalDevice();
            localDevice.setDiscoverable(DiscoveryAgent.GIAC);
            notifier = (StreamConnectionNotifier) Connector.open(serverUrl);
            ServiceRecord record = localDevice.getRecord(notifier);
            record.setAttributeValue(PLAYER_NAME_KEY, new DataElement(
                    DataElement.STRING, playerName));
            try {
                conn = notifier.acceptAndOpen();
            } catch (IOException ignored) {
                return;
            }
            LocalDevice.getLocalDevice().setDiscoverable(
                    DiscoveryAgent.NOT_DISCOVERABLE);
            notifier.close();
            fireConnectionEstablishedEvent();
        } catch (BluetoothStateException e) {
            fireConnectionErrorEvent(e);
        } catch (IOException e) {
            fireConnectionErrorEvent(e);
        }
    }
}